import React,{ Component } from 'react'
import {AtImagePicker} from 'taro-ui'
import {Upload} from "@/utils/Http";
import {getFullSrc} from "@/utils/Helper";

interface propsType {
  onChange?: (value) => void;
  onRef?: (value) => void;
  showAddBtn?: boolean;
  value: Array<{url: string}> | null;
  length: number
}

interface stateType {
  files: Array<{url: string}>
}


/**
 * 图片上传组件
 */
export default class ImageUploaders extends Component<propsType, stateType> {

  constructor(props) {
    super(props);
    const {value } = props;

    this.state = {
      files: (value || []).map(item => ({...item, url: getFullSrc(item.url)})) || [],
    };
  }

  triggerChange = value => {
    const {onChange} = this.props;
    if(onChange) onChange(value)
  }



  onFileChange = (fileList, operationType, index) => {
    if(operationType === 'add') {
      if(fileList && fileList.length) {
        fileList.forEach(async (item) => {
          const { url } = item;
          Upload(url).then(res => {
            if(res && res.url) {
              this.setState((prevState) => {
                const files = [...prevState.files, {...res, url:res.url}];
                this.triggerChange(files);
                return {
                  ...prevState,
                  files,
                }
              })
              const human_face=res.url
              const onRef= this.props

              if (onRef && human_face) {
                this.props.onRef(human_face);
              }
            }
          })
        })
      }
    } else if(operationType === 'remove') {
      const {files} = this.state;
      const newValue = files.filter((item, i) => i !== index)
      this.triggerChange(newValue);
      this.setState({
        files: newValue,
      })

    }

  }

  render () {
    const {showAddBtn, length} = this.props;
    const {files} = this.state;
    return (
      <AtImagePicker
        className={showAddBtn !== false? '' : 'image-picker-readonly'}
        showAddBtn={showAddBtn !== false}
        files={files}
        length={length}
        onChange={this.onFileChange}
      />
    )
  }
}
